<?php
function em_get_base_url() {
	return ( isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ) ? preg_replace('/http:/', 'https:', EM_BASE_URL) : EM_BASE_URL;
}

function em_uid() {
	return md5(uniqid(rand(), true));
}

function get_em_registration_uri() {
	return $em_page_link = str_replace(get_option("siteurl"), "", get_page_link(get_option('em_register_page')));
}

function em_can_admin_events() {
	global $current_user;

	$roles = explode(":", get_option('em_manager_role'));
	foreach ($current_user->roles as $role) {
		if (in_array($role, $roles)) {
			return true;
		}
	}

	return false;
}

function em_event_url($event_id) {
	global $wp_rewrite;
	$em_page_link = get_page_link(get_option('em_register_page'));
	if ($wp_rewrite->using_permalinks()) {
		$em_page_link .= '?event_id=' . $event_id;
	} else {
		$em_page_link .= '&event_id=' . $event_id;
	}
	return get_option('em_use_ssl')?str_replace("http://", "https://", $em_page_link):$em_page_link;
}


function em_render_form_field(&$question, $answer = "") {
	$required = '';
	if ($question->required == "Y") {
		$required = ' class="r"';
	}
	switch ($question->question_type) {
		case "TEXT":
			echo "<input type=\"text\"$required id=\"TEXT-$question->id\"  name=\"TEXT-$question->id\" size=\"40\" title=\"$question->question\" value=\"$answer->answer\" />\n";
			break;

		case "TEXTAREA":
			echo "<textarea id=\"TEXTAREA-$question->id\"$required name=\"TEXTAREA-$question->id\" title=\"$question->question\" cols=\"30\" rows=\"5\">$answer->answer</textarea>\n";
			break;

		case "SINGLE":
			$values = explode(",", $question->values);
			$answers = explode(",", $answer->answer);

			foreach ($values as $key => $value) {
				$checked = in_array($value, $answers)? " checked=\"checked\"": "";
				echo "<label><input id=\"MULTIPLE-$question->id-$key\"$required name=\"SINGLE-$question->id\" title=\"$question->question\" type=\"radio\" value=\"$value\"$checked /> $value</label><br/>\n";
			}
			break;

		case "MULTIPLE":
			$values = explode(",", $question->values);
			$answers = explode(",", $answer->answer);
			foreach ($values as $key => $value) {
				$checked = in_array($value, $answers)? " checked=\"checked\"": "";
				echo "<label><input type=\"checkbox\"$required id=\"MULTIPLE-$question->id-$key\" name=\"MULTIPLE-$question->id-$key\" title=\"$question->question\" value=\"$value\"$checked /> $value</label><br/>\n";
			}
			break;

		default:
			break;
	}
}

function em_list_events() {
	global $wpdb, $em_event_table;
	$events = $wpdb->get_results("select * from $em_event_table " .
			"where listing_status = 'Published' and event_end > now() " .
			"order by event_start desc ");

	if (isset($events)) {
		echo '<ul class="em-event-list">';
		foreach ($events as $event) {
			echo '<li><a href="' . em_event_url($event->id) . '">' . $event->event_name . '</a></li>';
		}
		echo '</ul>';
	} else {
		echo '<p>No events to register for at this time.</p>';
	}
}

function em_register_form() {
	global $wpdb, $em_event_table, $em_question_table, $em_registration_table, $reg_id;
	$event_id = $_REQUEST['event_id'];

	if (isset($event_id)) {
		$event = $wpdb->get_row("SELECT * from $em_event_table where id = '$event_id'");

		if (!$event || $event->listing_status == "Unpublished") {
			echo "<h2>Sorry, the event you are looking for was not found.</h2>";
			return;
		} else {
			require_once(ABSPATH . "wp-content/plugins/EventManager/register-form.php");
		}
	} else {

		echo '<h3>Please select an event to register for</h3>';
		em_list_events();
	}
}

function em_insert_participant() {
	global $wpdb,$em_registration_table,$em_question_table,$em_answer_table,$reg_id;

	$errors = array();

	$event_id = $_POST['event_id'];
	//$email_address= $_POST['email_address'] ? $_POST['email_address'] : em_uid() . "@noemail.com";
	$email_address= $_POST['email_address'];
	$first_name = $_POST['first_name'];
	$last_name = $_POST['last_name'];
	$address1 = $_POST['address1'];
	$address2 = $_POST['address2'];
	$city = $_POST['city'];
	$state = strtoupper($_POST['state']);
	$zip = $_POST['zip'];
	$phone = $_POST['phone'];

	if (empty($email_address)) $errors['email_address'] = "Email Address is empty.";

	if (count($errors) > 0 ) return $errors;

	$wpdb->query("INSERT into $em_registration_table (event_id, email_address, first_name, last_name,
				address1, address2, city, state, zip, phone, last_update_ts) values('$event_id', '$email_address',
				'$first_name', '$last_name', '$address1', '$address2', '$city', '$state', '$zip', '$phone', now())");

	$reg_id = $wpdb->get_var("SELECT LAST_INSERT_ID()");

	$questions = $wpdb->get_results("SELECT * from `$em_question_table` where event_id = '$event_id'");
	if ($questions)
	foreach ($questions as $question) {
		switch ($question->question_type) {
			case "TEXT":
			case "TEXTAREA":
			case "SINGLE":
				$post_val = $_POST[$question->question_type . '-' . $question->id];
				$wpdb->query("INSERT into `$em_answer_table` (registration_id, question_id, answer)
					values ('$reg_id', '$question->id', '$post_val')");
				break;
			case "MULTIPLE":
				$values = explode(",", $question->values);
				$value_string = '';
				foreach ($values as $key => $value) {
					$post_val = $_POST[$question->question_type . '-' . $question->id . '-' . $key];
					if ($key > 0 && !empty($post_val))
						$value_string .= ',';
					$value_string .= $post_val;
				}
				$wpdb->query("INSERT into `$em_answer_table` (registration_id, question_id, answer)
					values ('$reg_id', '$question->id', '$value_string')");
				break;
		}
	}
	return false;
}

function em_update_participant() {
	global $wpdb,$em_registration_table,$em_question_table,$em_answer_table;

	$registration_id = $_POST['registration_id'];
	$event_id = $_POST['event_id'];
	$email_address = $_POST['email_address'];
	$first_name = $_POST['first_name'];
	$last_name = $_POST['last_name'];
	$address1 = $_POST['address1'];
	$address2 = $_POST['address2'];
	$city = $_POST['city'];
	$state = $_POST['state'];
	$zip = $_POST['zip'];
	$phone = $_POST['phone'];

	$wpdb->query("UPDATE $em_registration_table set first_name = '$first_name', last_name = '$last_name',
				email_address = '$email_address', address1 = '$address1', address2 = '$address2', city = '$city', state = '$state',
				zip = '$zip', phone = '$phone', last_update_ts = now() where id = '$registration_id'");

	$wpdb->query("DELETE FROM $em_answer_table where registration_id = '$registration_id'");

	$questions = $wpdb->get_results("SELECT * from `$em_question_table` where event_id = '$event_id'");
	if ($questions)
	foreach ($questions as $question) {
		switch ($question->question_type) {
			case "TEXT":
			case "TEXTAREA":
			case "SINGLE":
				$post_val = $_POST[$question->question_type . '-' . $question->id];
				$wpdb->query("INSERT into `$em_answer_table` (registration_id, question_id, answer)
					values ('$registration_id', '$question->id', '$post_val')");
				break;
			case "MULTIPLE":
				$values = explode(",", $question->values);
				$value_string = '';
				foreach ($values as $key => $value) {
					$post_val = $_POST[$question->question_type . '-' . $question->id . '-' . $key];
					if ($key > 0 && !empty($post_val))
						$value_string .= ',';
					$value_string .= $post_val;
				}
				$wpdb->query("INSERT into `$em_answer_table` (registration_id, question_id, answer)
					values ('$registration_id', '$question->id', '$value_string')");
				break;
		}
	}
}